package com.sneakxy.cloudbase.platform.service;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.sneakxy.cloudbase.platform.bean.Menu;
import com.sneakxy.cloudbase.platform.bean.dto.MenuDTO;
import com.sneakxy.cloudbase.platform.repository.MenuRepository;
import com.sneakxy.mybatis.commons.repository.query.domain.CriteriaBuilder;

/**
 * 
 * @author 潜行的青衣
 * @see
 */
@Service
public class MenuService extends BaseService<Menu, String, MenuRepository> implements IMenuService {

	/* (non-Javadoc)
	 * @see com.sneakxy.cloudbase.platform.service.IMenuService#findByAccountId(java.lang.String)
	 */
	@Override
	public List<MenuDTO> findByAccountId(String accountId, String type) {
		List<MenuDTO> result = MenuDTO.from(getRepository().findByAccountId(accountId, type));
		Iterator<MenuDTO> it = result.iterator();
		MenuDTO menu = null;
		while(it.hasNext()) {
			menu = it.next();
			menu.setChildren(findByAccountId(accountId, menu.getId()));
			if(menu.getChildren().isEmpty() && StringUtils.isBlank(menu.getRouter())) {
				it.remove();
			}
		}
		return result;
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.cloudbase.platform.service.IMenuService#findTreeByType(java.lang.String)
	 */
	@Override
	public List<MenuDTO> findTreeByType(String type) {
		List<MenuDTO> result = MenuDTO.from(getRepository().findByType(type));
		result.forEach((menu) -> {
			menu.setChildren(findTreeByType(menu.getId()));
		});
		return result;
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.cloudbase.platform.service.IMenuService#hasChildren(java.lang.String)
	 */
	@Override
	public boolean hasChildren(String id) {
		CriteriaBuilder<Menu> builder = new CriteriaBuilder<>(Menu.class);
		builder.andEq("type", id);
		return this.getRepository().count(builder.build()) > 0;
	}

	@Override
	public boolean remove(String id) {
		if(!hasChildren(id)) {
			delete(id);
			return true;
		}
		return false;
	}

	@Override
	public void updatePermissionToNull(String permission) {
		getRepository().updatePermissionToNull(permission);
	}

}
